
if (typeof(bugs.ui) == "undefined") bugs.ui = {};

bugs.ui.DEFAULT_POPUP_OPTION = {
    title: null,
    css: "",
    modal: true,
    layout: "",
    alertButtons: true,
    closeButtons: true,
    onInit: function(popup) {},
    onOk: function(popup) {
        return true;
    },
    onCancel: function(popup) {
        return true;
    },
    onHide: function() {}
};

bugs.ui.modalLayer = {
    layer: null,
    show: function() {
        if (!this.layer) {
            this.layer = jQuery("<div></div>").attr("id", "_modalLayer").css({
                "z-index": "99",
                "filter": "alpha(opacity=30)",
                "opacity": "0.2",
                "-moz-opacity": "0.2",
                "position": "absolute",
                "top": 0,
                "left": 0,
                "background-color": "black"
            }).appendTo("body");
        }

        var width = jQuery(document).width();
        var height = jQuery(document).height();
        if (jQuery.browser.msie) {
            var bodyHeight = jQuery("body").height();
            var windowHeight = jQuery(window).height();
            /* Block layer 버그로 주석처리(영화,폰꾸미기등)
			try {
				var wrapHeight = jQuery("#wrap").height();
				
				height = (windowHeight > bodyHeight ? windowHeight : bodyHeight) > wrapHeight ? (windowHeight > bodyHeight ? windowHeight : bodyHeight) : wrapHeight;
			} catch (e) {
				height = windowHeight > bodyHeight ? windowHeight : bodyHeight;
			}
			*/
        }

        this.layer.css({
            width: "100%",
            height: height
        }).show();
    },
    show_dark: function() {
        if (!this.layer) {
            this.layer = jQuery("<div></div>").attr("id", "_modalLayer").css({
                "z-index": "99",
                "filter": "alpha(opacity=60)",
                "opacity": "0.6",
                "-moz-opacity": "0.6",
                "position": "absolute",
                "top": 0,
                "left": 0,
                "background-color": "black"
            }).appendTo("body");
        }

        var width = jQuery(document).width();
        var height = jQuery(document).height();
        if (jQuery.browser.msie) {
            var bodyHeight = jQuery("body").height();
            var windowHeight = jQuery(window).height();
        }

        this.layer.css({
            width: "100%",
            height: height
        }).show();
    },

    hide: function() {
        if (this.layer) this.layer.hide();

        if (typeof this.callLater == "function") {
            this.callLater();
            this.callLater = null;
        }
    },

    callLater: null
};

bugs.ui.TITLE_LOGO = "LOGO";

bugs.ui.popup = bugs.create();
bugs.ui.popup.prototype = {
    type: "popup",

    initialize: function(msg, option) {
        this.msg = msg;
        this.option = bugs.overed(bugs.clone(bugs.ui.DEFAULT_POPUP_OPTION), option || {});

        this.makeLayer();
    },

    makeLayer: function() {
        if (typeof(this.msg) == "string") {
            if (this.option.title == "layerLogin") this.layer = jQuery(this.getHtml2()).appendTo("body");
            else this.layer = jQuery(this.getHtml()).appendTo("body");
        } else {
            // 이미 있는 dom object로 레이어 생성
            this.layer = jQuery(this.msg).appendTo("body");
            if (this.layer.find("h1").length) {
                if (this.layer.find("h1 span.logo").length) this.option.title = bugs.ui.TITLE_LOGO;
                else this.option.title = this.layer.find("h1").html();
            }

            var css = new Array();
            this.layer.eachClass(function(index, item) {
                if (item == "layerPopup" || item == "layerAlert") return;

                css.push(item);
            }.bind(this));

            if (css.length == 1) this.option.css = css[0];
            else this.option.css = css;
        }
        if (this.option.title != "layerLogin") {
            this.layer.find("div.btnClose a").click(function() {
                this.hide();
                //실시간 스타방송 시 로그인 레이어가 뒤로 숨기 때문에 숨긴 플레시플레이어 레이어를 다시 보여준다.
                if (typeof castType != "undefined" && castType == "live") {
                    if ((jQuery(".layerAlert") && jQuery(".layerAlert").css("display") == "none" && jQuery(".layerPopup") && jQuery(".layerPopup").css("display") == "none") || (typeof jQuery(".layerAlert") != "undefined" && jQuery(".layerPopup") && jQuery(".layerPopup").css("display") == "none") || jQuery(".layerAlert") == null) {

                        showVideoLayerFlag = false;
                        showVideoLayer();
                    }
                }
                return false;
            }.bind(this));
            this.makeButtons();

        } else {
            jQuery("#layerLoginClose").click(function() {
                this.hide();
                return false;
            }.bind(this));
        }

        this.onInit();
    },

    makeButtons: function() {
        this.layer.find("a[type=ok]").unbind("click").click(function() {
            if (this.option.onOk(this)) this.hide();
            return false;
        }.bind(this));

        this.layer.find("button[btnType=ok]").unbind("click").click(function() {
            if (this.option.onOk(this)) this.hide();
        }.bind(this));

        this.layer.find("a[type=cancel]").unbind("click").click(function() {
            if (this.option.onCancel(this)) this.hide();
            return false;
        }.bind(this));
    },

    setTitle: function(title) {
        this.layer.find("h1:first").html(title);
    },

    getHtml: function() {
        var html = "<div class=\"layerPopup " + (!this.option.title ? "noTitle " : "") + this.option.css + "\" style=\"display:none;\">";

        if (this.option.title) {
            if (this.option.title == bugs.ui.TITLE_LOGO) html += "<h1><span class=\"logo\"><img src=\"" + g_urlFile + "/common/header/logo_bugsLayer.gif\" alt=\"Bugs!\" /></span></h1>";
            else html += "<h1>" + this.option.title + "</h1>";
        }

        html += "<div class=\"content\">" + this.msg + "<div class=\"btnClose\">";

        if (this.option.alertButtons) {
            html += "<a href=\"#\"><span>닫기</span></a>";
        }

        html += "</div>" + "</div>";

        if (!this.option.title) html += "<div class=\"layerBg bgTL\"></div>";

        html += "</div>";

        return html;
    },
    getHtml2: function() {
        var html = "<div class=\"layerLogin\" style=\"display:none;\">" + "<div class=\"bg\">" + this.msg + "<div class=\"btnClose\"><a href=\"javascript:void(0);\" id=\"layerLoginClose\"></a></div>" + "</div>" + "</div>";

        return html;
    },
    innerHtml: function(html) {
        if (typeof html != "undefined") {
            if (typeof(this.msg) == "string") {
                jQuery("div.content", this.layer).children().not("div.btnClose").remove();
                jQuery("div.content", this.layer).prepend(html);
                //jQuery("div.content", this.layer).html(html);				
            } else {
                this.layer.html(jQuery(this.msg).html());
            }
        }
    },
    onInit: function() {
        this.option.onInit(this);
    },

    show: function(msg, option) {
        if (msg) {
            if (this.type == "alert") this.layer.find("div.content > p").html(msg);
            else if (this.type == "alertMobile") this.layer.find("div.layerAlertWrap > p").html(msg);
            else {
                this.innerHtml(msg);
                this.makeButtons();
            }
        }

        if (!bugs.valid.isNull(option)) {
            option.onInit(this);
        }

        this.option = bugs.overed(this.option, option || {});
        var css = this.option.css;

        this.layer.eachClass(function(index, item) {
            if (item == "layerPopup" || item == "layerAlert") return;

            jQuery(this).removeClass(item);
        }.bind(this.layer));

        if (typeof(this.option.css) == "object") {
            for (var i in this.option.css)
            this.layer.addClass(this.option.css[i]);
        } else this.layer.addClass(css);

        //----- modal dialog 처리 -----------------------------------------------
        if (this.option.modal) {
            if (this.option.title == "layerLogin") bugs.ui.modalLayer.show_dark();
            else bugs.ui.modalLayer.show();
        }
        //---------------------------------------------------------------------

        var left = jQuery(window).scrollLeft() + ((jQuery(window).width() - this.layer.width()) >> 1);
        var top = jQuery(window).scrollTop() + ((jQuery(window).height() - this.layer.height()) >> 1);

        this.layer.css({
            left: left,
            top: top
        }).show();

        return this;
    },

    hide: function() {
        if (this.option.modal) bugs.ui.modalLayer.hide();
        if (this.option.onHide) this.option.onHide();
        this.layer.hide(
        //jQuery.proxy(function() { this.remove(); }, this)
        );

    },

    addModalMsg: function(id, msg) {
        var html = "" + "<div class=\"layerModal\" style=\"top:0px;display:none;\">" + "	<div class=\"content\">" + "		<p>" + msg + "</p>" + "		<div class=\"btnArea\"><span class=\"button typeME\"><a href=\"#\">확인</a></span></div>" + "	</div>" + "	<div class=\"layerBg bgTR\"></div>" + "	<div class=\"layerBg bgTL\"></div>" + "</div>";

        this.modalMsgList[id] = jQuery(html).appendTo(this.layer);
    },

    showModalMsg: function(msg, option) {
        this.option = bugs.overed(this.option, option || {});
        if (!this.modalMsgLayer) {
            var html = "" + "<div class=\"layerModal\" style=\"top:0px;display:none;\">" + "	<div class=\"content\">" + "		<p></p>" + "		<div class=\"btnArea\"><span class=\"button typeME\"><a href=\"#\">확인</a></span></div>" + "	</div>" + "	<div class=\"layerBg bgTR\"></div>" + "	<div class=\"layerBg bgTL\"></div>" + "</div>";

            this.modalMsgLayer = jQuery(html).appendTo(this.layer).find("div.btnArea a").click(function() {
                this.modalMsgLayer.hide();
                this.option.onOk();
                return false;
            }.bind(this)).end();
        }
        this.modalMsgLayer.find("div.content p").html(msg);
        var left = (this.modalMsgLayer.parent().width() - this.modalMsgLayer.width()) >> 1;
        var top = (this.modalMsgLayer.parent().height() - this.modalMsgLayer.height()) >> 1;
        this.modalMsgLayer.css({
            top: top,
            left: left
        }).show();

    },

    getLayer: function() {
        return this.layer;
    },

    reposition: function() {
        var left = jQuery(window).scrollLeft() + ((jQuery(window).width() - this.layer.width()) >> 1);
        var top = jQuery(window).scrollTop() + ((jQuery(window).height() - this.layer.height()) >> 1);

        this.layer.css({
            left: left,
            top: top
        });
    },
    remove: function() {
        if (this.layer) this.layer.remove();
        this.layer == null;
    }
};

bugs.ui.loadingLayer = bugs.create();
bugs.ui.loadingLayer.prototype = {
    html: '<div class="layerAlert layerLoading" style="left: 250px; top: 300px; display: none; border-width:1px; ">' + '<div class="content">' + '<p><%=obj.title%></p>' + '</div>' + '<div class="layerBg bgTR"></div>' + '<div class="layerBg bgTL"></div>' + '</div>',
    initialize: function(title, option) {
        this.title = title;
        var tmp = new bugs.template(this.html, {
            title: title
        });
        this.layer = jQuery(tmp.html()).appendTo("body");

    },
    show: function(css) {
        if (typeof css == "undefined") {
            css = {
                position: "absolute",
                left: "50%",
                top: 316,
                "margin-left": -146
            };
        }
        this.layer.css(css).show();

    },
    hide: function() {
        this.layer.hide();
    },
    remove: function() {
        this.layer.remove();
    }
}

bugs.ui.alert = bugs.create();
bugs.ui.alert.prototype = {
    getHtml: function() {
        var _layerClass = "layerAlert";
        if (typeof this.option.layerClass != "undefined") _layerClass = this.option.layerClass;

        var html = "<div class=\"" + _layerClass + " " + this.option.css + "\" style=\"display:none;\">" + "<div class=\"content\"><p></p>";

        if (this.option.alertButtons) {
            html += "<div class=\"btnArea\">" + "<span class=\"button typeME\"><a href=\"javascript:void(0);\">확인</a></span>" + "</div>";
        }

        html += "</div>";

        if (this.option.alertButtons) html += "<div class=\"btnClose\"><a href=\"#\"><span>닫기</span></a></div>";

        html += "<div class=\"layerBg bgTR\"></div>" + "<div class=\"layerBg bgTL\"></div>" + "</div>";

        return html;
    },

    onInit: function() {
        this.type = "alert";

        this.layer.find("div.content > p").html(this.msg);

        this.layer.find("span.button a").click(function() {
            this.hide();
            if (typeof(this.option.onOk) == "function") this.option.onOk(this);
            return false;
        }.bind(this));

        this.layer.find(".btnClose a").click(function() {
            this.hide();
            if (typeof(this.option.onCancel) == "function") this.option.onCancel(this);
            return false;
        }.bind(this));


        if (typeof this.option.onInit == "function") {
            this.option.onInit(this);
        }
    }
};
bugs.extend(bugs.ui.alert, bugs.ui.popup);

bugs.ui.alert.mobile = bugs.create();
bugs.ui.alert.mobile.prototype = {
    getHtml: function() {
        var _layerClass = "layerAlert";
        if (typeof this.option.layerClass != "undefined") _layerClass = this.option.layerClass;

        if ("tiles" == this.option.layout) {
            var html = "<div class=\"" + _layerClass + " " + this.option.css + "\" style=\"display:none;\">" + "	<div class=\"layerAlertWrap\">" + "		<p></p>";

            if (this.option.alertButtons) {
                html += "		<div class=\"btnArea\"></div>";
            }

            if (this.option.closeButtons) {
                html += "		<div class=\"closeArea\"><p class=\"close\">닫기</p></div>";
            }

            html += "	</div>" + "</div>";
        } else {
            var html = "<div class=\"" + _layerClass + " " + this.option.css + "\" style=\"display:none;\">" + "	<div class=\"layerAlertWrap\">" + "		<p></p>";

            if (this.option.alertButtons) {
                html += "		<div class=\"btnArea\">" + "			<a href=\"javascript:void(0);\" class=\"button btnTypeM\">확인</a>" + "		</div>";
            }

            html += "	</div>" + "</div>";
        }


        return html;
    },

    onInit: function() {
        this.type = "alertMobile";

        this.layer.find("div.layerAlertWrap > p").html(this.msg);

        if (!bugs.valid.isNull(this.option.buttons)) {
            this.layer.find("div.layerAlertWrap > div.btnArea").empty().html(this.option.buttons);
        }

        if ("tiles" == this.option.layout) {
            this.layer.find("div.layerAlertWrap p.close").click(function() {
                this.hide();
                if (typeof(this.option.onCancel) == "function") this.option.onCancel(this);
                return false;
            }.bind(this));
        } else {
            this.layer.find("div.btnArea a.button").click(function() {
                this.hide();
                if (typeof(this.option.onOk) == "function") this.option.onOk(this);
                return false;
            }.bind(this));
        }

        if (typeof this.option.onInit == "function") {
            this.option.onInit(this);
        }
    }
};
bugs.extend(bugs.ui.alert.mobile, bugs.ui.popup);

bugs.ui.showPopup = function(msg, option) {
    if (!bugs.ui._popup) bugs.ui._popup = new bugs.ui.popup(msg, option).show();
    else bugs.ui._popup.show(msg, bugs.overed(bugs.clone(bugs.ui.DEFAULT_POPUP_OPTION), option || {}));
};

bugs.ui.showAlert = function(msg, option) {
    if (!bugs.ui._alert) bugs.ui._alert = new bugs.ui.alert(msg, option).show();
    else bugs.ui._alert.show(msg, bugs.overed(bugs.clone(bugs.ui.DEFAULT_POPUP_OPTION), option || {}));
};

bugs.ui.showAlertMobile = function(msg, option) {
    if (!bugs.ui._alertMobile) bugs.ui._alertMobile = new bugs.ui.alert.mobile(msg, option).show();
    else bugs.ui._alertMobile.show(msg, bugs.overed(bugs.clone(bugs.ui.DEFAULT_POPUP_OPTION), option || {}));
};

bugs.ui.showLoginAlert = function(code, option) {
    var opt = bugs.overed({
        msrl: "",
        layerLogin: true,
        css: "layerLoginMsg"
    }, option || {});

    if (code != "OK") {
        switch (code) {
            case "VSTATC":
                if (!bugs.object.empty(opt.msrl)) {
                    var popUp = window.open(g_urlMember + "/join/parentAgreeEmail/popup/" + opt.msrl, "parentAgree", "width=582,height=560,resizable=0");
                    popUp.focus();
                } else {
                    bugs.ui.showAlert("잘못된 로그인 정보입니다.", opt);
                }
                break;
            case "CHECK_NAME_SSN":
                var msg = "<p>" + "	현재 회원님은 회원 가입 시 입력한 정보 중<br />" + "	로그인시 반드시 필요한 정보에 문제(누락)가 있어<br />" + "	로그인이 불가능합니다.<br /> " + "	정상적으로 로그인을 하시려면<br />" + "	<a href=\"http://helpdesk.bugs.co.kr\">벅스고객센터</a>로 문의해 주시기 바랍니다." + "	</p> " + "	<div class=\"btnArea\"><span class=\"button typeME\"><a href=\"javascript:void(0);\">확인</a></span></div>";
                bugs.ui.showPopup(msg, {
                    title: "로그인 불가 안내",
                    css: "layerLoginError",
                    onInit: function(popup) {
                        popup.getLayer().find("span.typeME a").click(function() {
                            popup.hide();
                            if (typeof(popup.option.onOk) == "function") popup.option.onOk();
                            return false;
                        });
                    }
                });
                break;
            case "PAUSE":
                bugs.ui.showAlert("일시 정지된 아이디입니다.", opt);
                break;
            case "ALREADY_LOGGED":
                bugs.ui.showAlert("이미 로그인 되어 있습니다.", opt);
                break;
            case "NSUR":
                if (opt.layerLogin) {
                    bugs.ui.showLoginLayer();
                }
                bugs.ui.showAlert("벅스에 등록되지 않는 아이디입니다.", opt);
                break;
            case "WPWD":
                if (opt.layerLogin) {
                    bugs.ui.showLoginLayer();
                }
                bugs.ui.showAlert("입력하신 비밀번호가 맞지 않습니다.", opt);
                break;
            default:
                if (opt.layerLogin) {
                    bugs.ui.showLoginLayer();
                }
                bugs.ui.showAlert("올바른 아이디/비밀번호를 찾아<br />입력하여 주세요.", opt);

                break;
        }
    } else {
        //Pc 정보 추출
        var f_ver = swfobject.getFlashPlayerVersion();
        var browserName; //브라우저명
        var browserVer; //브라우저 버전
        var browserLang; //브라우저 언어
        var browserResolution; //해상도
        var browserWidth; //최대 가로길이
        var browserHeight; //최대 세로길이
        var browserOS = "Win"; //OS종류
        var browserFlashVer; //flash버전

        browserWidth = 0; // 초기화
        browserHeight = 0; // 초기화

        if (navigator.appName.match(/Explorer/i)) {
            browserName = navigator.appName;
            browserVer = navigator.appVersion.match(/MSIE \d+.\d+/)[0].split(" ")[1];
        } else if (navigator.appName.match(/opera/i)) {
            browserName = navigator.appName;
            browserVer = window.opera.version();
        } else if (navigator.appName.match(/Netscape/i)) {
            if (navigator.appVersion.match(/RockMelt/i)) {
                browserName = "RockMelt";
                browserVer = navigator.appVersion.match(/\d+.\d+.\d+.\d+ /)[0].split(" ")[0];
            } else if (navigator.appVersion.match(/chrome/i)) {
                browserName = "Chrome";
                browserVer = navigator.appVersion.match(/\d+.\d+.\d+.\d+ /)[0].split(" ")[0];
            } else if (navigator.appVersion.match(/safari/i)) {
                browserName = "Safari";
                browserVer = navigator.appVersion.match(/\d+.\d+.\d +Safari/)[0].split(" ")[0];
            } else {
                browserName = "Firefox";
                browserVer = navigator.userAgent.match(/rv:\d+.\d+.\d/)[0].split(":")[1];
            }
        }
        if (navigator.userAgent.indexOf('Mac') != -1) {
            browserOS = "Mac";
        }
        browserLang = navigator.browserLanguage;
        browserResolution = screen.width + " x " + screen.height;
        browserWidth = screen.availWidth;
        browserHeight = screen.availHeight;
        browserFlashVer = f_ver.major + "." + f_ver.minor + "." + f_ver.release;
        if (browserWidth == null || browserHeight == null) {
            browserWidth = 0;
            browserHeight = 0;
        }
        if (browserWidth == "" || browserHeight == "") {
            browserWidth = 0;
            browserHeight = 0;
        }

        objParams = {
            browserName: browserName,
            browserVer: browserVer,
            browserLang: browserLang,
            browserResolution: browserResolution,
            browserWidth: browserWidth,
            browserHeight: browserHeight,
            browserOS: browserOS,
            browserFlashVer: browserFlashVer,
            decorator: "blank"
        };
        try {
            jQuery.post(
            g_urlAjax + "/logging/pcLogInsert",
            objParams,

            function(response) {
                //location.href=g_urlWww+"/index/";	
            });
        } catch (e) {}
    }
}


bugs.ui.showLoginLayer = function(option) {
    var opt = bugs.overed({
        rUrl: location.href,
        openWindow: false,
        rType: "X"
    }, option || {});

    var saveId = bugs.cookie.get('saveId');
    if (!bugs.ui._loginLayer) {
        var msg = "" + "<div class=\"login\" >" + "	<form method=\"post\" id=\"frmLoginLayer\" name=\"frmLoginLayer\" action=\"" + g_urlMember + "/login/process\" onSubmit=\"return false;\">" + "	<div class=\"bugsID\">" + "	<h3><span>벅스 아이디로 로그인</span></h3>" + "	<div class=\"help\">";
        if (opt.rType != "X") {
            msg += "	<span class=\"signup\"><a href=\"" + g_urlMember + "/join/memberMain?rUrl=" + encodeURIComponent(opt.rUrl) + "\">회원가입</a></span>";
        } else {
            msg += "	<span class=\"signup\"><a href=\"" + g_urlMember + "/join/memberMain\">회원가입</a></span>";
        }

        msg += "		<span class=\"forgot\"><a href=\"" + g_urlMember + "/find/id?wl_ref=new_gnb\">아이디</a> / <a href=\"" + g_urlMember + "/find/pw?wl_ref=new_gnb\">비밀번호 찾기</a></span>" + "	</div>" + "	<fieldset class=\"loginForm\">" + "		<legend>벅스 아이디로 로그인</legend>" + "		<span class=\"inputInfo\">" + "			<span class=\"username\"><label for=\"user_id\" id=\"label__id\" onclick=\"jQuery('#user_id').trigger('focus');\">벅스 또는 피망플러스 아이디</label> <input type=\"text\" name=\"user_id\" id=\"user_id\" class=\"text\" maxlength=\"100\" tabindex=\"101\" style=\"ime-mode:disabled\" /></span>" + "			<span class=\"password\"><label for=\"passwd\" id=\"label__pw\" onclick=\"jQuery('#passwd').trigger('focus');\">비밀번호</label> <input type=\"password\" name=\"passwd\" id=\"passwd\" class=\"text\" maxlength=\"20\" tabindex=\"102\" /></span>" + "		</span>" + "		<button type=\"button\" class=\"btnBugsLogin btnLogin\"  tabindex=\"3\">로그인</button>" + "		<div class=\"loginOption\">" + "			<span><input type=\"checkbox\" name=\"checkSaveId\" id=\"checkSaveId\" class=\"checkbox\" value=\"1\" /><label for=\"checkSaveId\">ID 저장</label></span>" + "			<input type=\"checkbox\" name=\"checkSsl\" id=\"checkSsl\" class=\"checkbox\" value=\"1\" checked=\"checked\" disabled /><label for=\"checkSsl\">보안접속</label>" + "		</div>" + "	</fieldset>" + "</div>" + "<div class=\"facebookID\">" + "	<h3><span>페이스북 계정으로 로그인</span></h3>" + "	<p>Facebook 계정으로 간편하게<br />로그인 후, 벅스 서비스를<br />이용하실 수 있습니다.</p>" + "	<a href=\"javascript:void(0);\" class=\"btnFBLogin facebookLogin\" id=\"fb-auth-layer\" >로그인</a> " + "</div>";

        if (option != null && option.encodeType != null && option.encodeType != undefined) {
            msg += "		<input type=\"hidden\" id=\"encode\" name=\"encode\" value=\"" + option.encodeType + "\"  />";
        }
        msg += "		<input type=\"hidden\" id=\"rUrl\" name=\"rUrl\" value=\"" + opt.rUrl + "\"  />";
        "	</form>" + "	</div>";


        bugs.ui._loginLayer = new bugs.ui.popup(msg, {
            title: "layerLogin",
            css: "layerLogin",
            onInit: function(popup) {
                var id = popup.layer.find("#frmLoginLayer input#user_id");
                var passwd = popup.layer.find("#frmLoginLayer input#passwd");

                //bugs.focusNblur(jQuery("#user_id,#passwd"));
                jQuery(id).focus(function() {
                    jQuery(this).addClass("focus");
                }).blur(function() {
                    jQuery(this).removeClass("focus");
                    if (jQuery(this).val().length == 0) jQuery('#label__id').show();
                }).keyup(function() {
                    if (jQuery(this).val().length == 0) jQuery('#label__id').show();
                    else jQuery('#label__id').hide();
                });

                jQuery(passwd).focus(function() {
                    jQuery(this).addClass("focus");
                }).blur(function() {
                    jQuery(this).removeClass("focus");
                    if (jQuery(this).val().length == 0) jQuery('#label__pw').show();
                }).keyup(function() {
                    if (jQuery(this).val().length == 0) jQuery('#label__pw').show();
                    else jQuery('#label__pw').hide();
                });

                var saveId = bugs.cookie.get('saveId');
                if (!bugs.valid.empty(saveId)) {
                    id.val(saveId).focus();
                    jQuery('#label__id').hide();
                    jQuery("#checkSaveId").attr("checked", "checked");
                }

                jQuery("#checkAutoLogin").click(function() {
                    if (jQuery(this).is(":checked")) {
                        var show = bugs.cookie.get('autoLogin');
                        if (show != "Y") {
                            bugs.layermenu.showClickLayer('.autoLoginAlert');
                        }
                    } else {
                        jQuery('.autoLoginAlert').hide();
                    }
                });


                try {
                    var Dns = location.href;
                    if (Dns.indexOf("sing.bugs") != -1 || Dns.indexOf("helpdesk.bugs") != -1 || Dns.indexOf("movie.bugs") != -1 || Dns.indexOf("game.bugs") != -1 || Dns.indexOf("shotonline.bugs") != -1 || Dns.indexOf("audition.bugs") != -1) jQuery('#fb-auth-layer').click(function(event) {
                        alert('서비스 준비 중입니다.');
                    });
                    else {

                        jQuery('#fb-auth-layer').click(function(event) {
                            bugs.fb.openLogin();
                        });
                        window.fbAsyncInit = function() {
                            FB.init({
                                appId: '122936701116206',
                                //channelUrl : 'http://www.bugs.co.kr/channel.html', // Channel File 
                                status: true,
                                cookie: true,
                                xfbml: true,
                                oauth: true
                            });
                        };
                        (function() {
                            var e = document.createElement('script');
                            e.async = true;
                            e.src = document.location.protocol + '//connect.facebook.net/ko_KR/all.js';
                            document.getElementById('fb-root').appendChild(e);
                        }());
                    }
                } catch (e) {}

                jQuery("#layerOpenCheckAotoLogin2").click(function() {
                    var oDate = new Date();
                    oDate.setDate(oDate.getDate() + 365);
                    bugs.cookie.set('autoLogin', "Y", oDate, "/", "bugs.co.kr");

                    jQuery('.autoLoginAlert').hide();
                });

                var _submitFunc = function() {
                    if (bugs.valid.empty(id.val())) {
                        alert("아이디를 입력해주세요!");
                        return false;
                    }
                    if (bugs.valid.empty(passwd.val())) {
                        alert("비밀번호를 입력해주세요!");
                        return false;
                    }

                    var oDate = new Date();
                    if (jQuery("#checkSaveId").is(":checked")) {
                        oDate.setDate(oDate.getDate() + 30);
                        bugs.cookie.set("saveId", id.val(), oDate, "/", "bugs.co.kr");
                    } else {
                        oDate.setDate(oDate.getDate() - 1);
                        bugs.cookie.set("saveId", "", oDate, "/", "bugs.co.kr");
                    }

                    jQuery("#frmLoginLayer").submit();
                };

                popup.layer.find("button.btnLogin").click(_submitFunc);
                jQuery(passwd).keypress(function(event) {
                    if (event.keyCode == '13') {
                        _submitFunc();
                        return false; //비프음 제거
                    }
                });

                jQuery(id).keypress(function(event) {
                    if (event.keyCode == '13') {
                        _submitFunc();
                        return false; //비프음 제거
                    }
                });

                //웹플레이어에서 로그인 실패 후 자동으로 뜨는 로그인 레이어에서 링크 버튼(회원가입, 비번, id 찾기 클릭 시 새창으로 뜨도록 변경) 
                if (location.href.indexOf("player?trackId=") > -1) opt.openWindow = true;

                if (opt.openWindow) {
                    if (typeof opt.callback == "function") {
                        opt.callback();
                    }
                    popup.layer.find("span.signup a").openWindow(function() {
                        popup.hide();
                    });
                    popup.layer.find("span.forgot a").openWindow(function() {
                        popup.hide();
                    });
                }

            }
        }).show();
    } else {
        bugs.ui._loginLayer.layer.find("#rUrl").val(opt.rUrl);
        bugs.ui._loginLayer.show();
    }

    jQuery("#user_id").focus();

    //실시간 스타방송 때문에 로그인 레이어가 플래시플레이어 뒤로 숨기때문에 플래시플레이어 레이어 숨김
    if (typeof castType != "undefined" && castType == "live") {
        hideVideoLayer();
    }
};

// 오디션에서는 로딩 시 로그인 레이어가 생성되어 있어야 함.
bugs.ui.createLoginLayer = function(option) {
    var opt = bugs.overed({
        rUrl: location.href,
        openWindow: false,
        rType: "X"
    }, option || {});

    var saveId = bugs.cookie.get('saveId');
    if (!bugs.ui._loginLayer) {
        var msg = "" + "<div class=\"login\" >" + "	<form method=\"post\" id=\"frmLoginLayer\" name=\"frmLoginLayer\" action=\"" + g_urlMember + "/login/process\" onSubmit=\"return false;\">" + "	<div class=\"bugsID\">" + "	<h3><span>벅스 아이디로 로그인</span></h3>" + "	<div class=\"help\">";
        if (opt.rType != "X") {
            msg += "	<span class=\"signup\"><a href=\"" + g_urlMember + "/join/memberMain?rUrl=" + encodeURIComponent(opt.rUrl) + "\">회원가입</a></span>";
        } else {
            msg += "	<span class=\"signup\"><a href=\"" + g_urlMember + "/join/memberMain\">회원가입</a></span>";
        }

        msg += "		<span class=\"forgot\"><a href=\"" + g_urlMember + "/find/id?wl_ref=new_gnb\">아이디</a> / <a href=\"" + g_urlMember + "/find/pw?wl_ref=new_gnb\">비밀번호 찾기</a></span>" + "	</div>" + "	<fieldset class=\"loginForm\">" + "		<legend>벅스 아이디로 로그인</legend>" + "		<span class=\"inputInfo\">" + "			<span class=\"username\"><label for=\"user_id\" id=\"label__id\" onclick=\"jQuery('#label__id').hide();\">아이디</label> <input type=\"text\" name=\"user_id\" id=\"user_id\" class=\"text\" onfocus=\"jQuery('#label__id').hide();\" maxlength=\"100\" tabindex=\"101\" /></span>" + "			<span class=\"password\"><label for=\"passwd\" id=\"label__pw\" onclick=\"jQuery('#label__pw').hide();jQuery('#passwd').trigger('focus');\">비밀번호</label> <input type=\"password\" name=\"passwd\" id=\"passwd\" class=\"text\" onfocus=\"jQuery('#label__pw').hide();\" maxlength=\"20\" tabindex=\"102\" /></span>" + "		</span>" + "		<button type=\"button\" class=\"btnBugsLogin btnLogin\"  tabindex=\"3\">로그인</button>" + "		<div class=\"loginOption\">" + "			<span><input type=\"checkbox\" name=\"checkSaveId\" id=\"checkSaveId\" class=\"checkbox\" value=\"1\" /><label for=\"checkSaveId\">ID 저장</label></span>" + "			<input type=\"checkbox\" name=\"checkSsl\" id=\"checkSsl\" class=\"checkbox\" value=\"1\" checked=\"checked\" disabled /><label for=\"checkSsl\">보안접속</label>" + "		</div>" + "	</fieldset>" + "</div>" + "<div class=\"facebookID\">" + "	<h3><span>페이스북 계정으로 로그인</span></h3>" + "	<p>Facebook 계정으로 간편하게<br />로그인 후, 벅스 서비스를<br />이용하실 수 있습니다.</p>" + "	<a href=\"javascript:void(0);\" class=\"btnFBLogin facebookLogin\" id=\"fb-auth-layer\" >로그인</a> " + "</div>";

        if (option != null && option.encodeType != null && option.encodeType != undefined) {
            msg += "		<input type=\"hidden\" id=\"encode\" name=\"encode\" value=\"" + option.encodeType + "\"  />";
        }
        msg += "		<input type=\"hidden\" id=\"rUrl\" name=\"rUrl\" value=\"" + opt.rUrl + "\"  />";
        "	</form>" + "	</div>";


        bugs.ui._loginLayer = new bugs.ui.popup(msg, {
            title: "layerLogin",
            css: "layerLogin",
            onInit: function(popup) {
                var id = popup.layer.find("#frmLoginLayer input#user_id");
                var passwd = popup.layer.find("#frmLoginLayer input#passwd");

                //bugs.focusNblur(jQuery("#user_id,#passwd"));
                jQuery(id).focus(function() {
                    jQuery(this).addClass("focus");
                }).blur(function() {
                    jQuery(this).removeClass("focus");
                });

                jQuery(passwd).focus(function() {
                    jQuery(this).addClass("focus");
                }).blur(function() {
                    jQuery(this).removeClass("focus");
                });

                var saveId = bugs.cookie.get('saveId');
                if (!bugs.valid.empty(saveId)) {
                    id.val(saveId).focus();
                    jQuery("#checkSaveId").attr("checked", "checked");
                }

                jQuery("#checkAutoLogin").click(function() {
                    if (jQuery(this).is(":checked")) {
                        var show = bugs.cookie.get('autoLogin');
                        if (show != "Y") {
                            bugs.layermenu.showClickLayer('.autoLoginAlert');
                        }
                    } else {
                        jQuery('.autoLoginAlert').hide();
                    }
                });


                try {
                    var Dns = location.href;
                    if (Dns.indexOf("sing.bugs") != -1 || Dns.indexOf("helpdesk.bugs") != -1 || Dns.indexOf("movie.bugs") != -1 || Dns.indexOf("game.bugs") != -1 || Dns.indexOf("shotonline.bugs") != -1 || Dns.indexOf("audition.bugs") != -1) jQuery('#fb-auth-layer').click(function(event) {
                        alert('서비스 준비 중입니다.');
                    });
                    else {

                        jQuery('#fb-auth-layer').click(function(event) {
                            bugs.fb.openLogin();
                        });
                        window.fbAsyncInit = function() {
                            FB.init({
                                appId: '122936701116206',
                                //channelUrl : 'http://www.bugs.co.kr/channel.html', // Channel File 
                                status: true,
                                cookie: true,
                                xfbml: true,
                                oauth: true
                            });
                        };
                        (function() {
                            var e = document.createElement('script');
                            e.async = true;
                            e.src = document.location.protocol + '//connect.facebook.net/ko_KR/all.js';
                            document.getElementById('fb-root').appendChild(e);
                        }());
                    }
                } catch (e) {}

                jQuery("#layerOpenCheckAotoLogin2").click(function() {
                    var oDate = new Date();
                    oDate.setDate(oDate.getDate() + 365);
                    bugs.cookie.set('autoLogin', "Y", oDate, "/", "bugs.co.kr");

                    jQuery('.autoLoginAlert').hide();
                });

                var _submitFunc = function() {
                    if (bugs.valid.empty(id.val())) {
                        alert("아이디를 입력해주세요!");
                        return false;
                    }
                    if (bugs.valid.empty(passwd.val())) {
                        alert("비밀번호를 입력해주세요!");
                        return false;
                    }

                    var oDate = new Date();
                    if (jQuery("#checkSaveId").is(":checked")) {
                        oDate.setDate(oDate.getDate() + 30);
                        bugs.cookie.set("saveId", id.val(), oDate, "/", "bugs.co.kr");
                    } else {
                        oDate.setDate(oDate.getDate() - 1);
                        bugs.cookie.set("saveId", "", oDate, "/", "bugs.co.kr");
                    }

                    jQuery("#frmLoginLayer").submit();
                };

                popup.layer.find("button.btnLogin").click(_submitFunc);
                popup.layer.find("input:text, input:password").keypress(function(event) {
                    if (event.keyCode == '13') {
                        _submitFunc();
                        return false;
                    }
                });

                //웹플레이어에서 로그인 실패 후 자동으로 뜨는 로그인 레이어에서 링크 버튼(회원가입, 비번, id 찾기 클릭 시 새창으로 뜨도록 변경) 
                if (location.href.indexOf("player?trackId=") > -1) opt.openWindow = true;

                if (opt.openWindow) {
                    popup.layer.find("span.signup a").openWindow(function() {
                        popup.hide();
                    });
                    popup.layer.find("span.forgot a").openWindow(function() {
                        popup.hide();
                    });
                }

            }
        });
    }
};

// CP 에서 접근하는 로그인은 모두 팝업으로 처리한다.
bugs.ui.showLoginPopup = function(option) {
    var opt = bugs.overed({
        cp: "",
        rUrl: ""
    }, option || {});

    jQuery.fn.popupWindow({
        url: g_urlSecure + "/login/popup?cp=" + opt.cp + "&rUrl=" + encodeURIComponent(opt.rUrl),
        name: "LoginPopup",
        width: 251,
        height: 174,
        center: 1
    });
};

bugs.ui.alertAdultNotice = function() {
    var msg = "해당곡은 청소년 유해매체물로서 정보통신망<br />" + "이용 촉진 및 정보보호 등에 관한 법률 및<br />" + "청소년보호법의 규정에 의하여<br />" + "19세 미만의 청소년이 이용할 수 없습니다. ";
    var _alert = new bugs.ui.showAlert(msg, {
        css: "layerAdultNotice"
    });
    //_alert.show();
};

bugs.ui.alertHoldBackNotice = function(type) {
    var msg = "해당 " + (type == "mv" ? "뮤직비디오는" : "곡은") + " 음원 권리사의<br />" + "요청(홀드백)으로 발매 후 일정기간<br />" + "1분 미리" + (type == "mv" ? "보기" : "듣기") + "만 가능합니다.";
    var _alert = new bugs.ui.showAlert(msg, {
        css: "layerAdultNotice"
    });
    //_alert.show();
};

bugs.ui.alertFacebookCpNotice = function() {
    var msg = '<p>페이스북 계정으로 로그인 시,<br />선택하신 서비스는 이용이 불가능합니다.</p><div class="btnArea"><span class="button typeME"><a href="javascript:void(bugs.ui.modalLayer.hide());" type="ok">확인</a></span></div><div class="btnClose"><a href="#"><span>닫기</span></a></div>';
    var popup = new bugs.ui.popup(msg, {
        title: "LOGO",
        css: "layerFbServiceNot"
    });
    popup.show();
};

bugs.ui.alertPmangPlusNotice = function() {
    var msg = '<p>피망플러스 계정으로 로그인 시,<br />선택하신 서비스는 이용이 불가능합니다.</p><div class="btnArea"><span class="button typeME"><a href="javascript:void(bugs.ui.modalLayer.hide());" type="ok">확인</a></span></div><div class="btnClose"><a href="#"><span>닫기</span></a></div>';
    var popup = new bugs.ui.popup(msg, {
        title: "LOGO",
        css: "layerFbServiceNot"
    });
    popup.show();
};

//----- clipboard 카피 버튼 -------------------------------------------------------
bugs.ui.clipboardButtonManager = {
    id: 1,

    buttons: {},

    getUniqueId: function() {
        return bugs.ui.clipboardButtonManager.id++;
    },

    handleEvent: function(event, id) {
        if (this.buttons[id]) this.buttons[id].handleEvent(event);
    }
};

bugs.ui.clipboardButton = bugs.create();
bugs.ui.clipboardButton.prototype = {
    containerId: "BugsClipboardUtilContainer",

    id: 0,

    initialize: function(selector, option) {
        this.id = bugs.ui.clipboardButtonManager.getUniqueId();
        bugs.ui.clipboardButtonManager.buttons[this.id] = this;

        this.button = jQuery(selector).mouseover(this.reposition.bind(this));
        this.option = bugs.overed({
            copyData: "",
            addClass: "",
            zIndex: 100,
            onComplete: function() {}
        }, option || {});

        if (jQuery("#" + this.containerId).length > 0) {
            this.container = jQuery("#" + this.containerId);
            this.swf = jQuery("#BugsClipboardUtil")[0];
            if (this.swf.tagName == "DIV") this.swf = null;
        } else {
            // firefox에서는 일단 화면에 플래쉬가 보여야 ExternalInterface.addCallback()이 되기 때문에
            // 일단 화면에 보이게끔 scrollTop으로 container를 생성함
            var top = jQuery(document).scrollTop();
            this.container = jQuery("<div id=\"" + this.containerId + "\"><div id=\"BugsClipboardUtil\"></div></div>").appendTo("body").css({
                position: "absolute",
                width: 10,
                height: 10,
                top: top,
                "z-index": this.option.zIndex
            });

            var flashvars = {
                id: this.id,
                copyData: this.option.copyData,
                eventHandler: "bugs.ui.clipboardButtonManager.handleEvent"
            };

            var params = {
                wmode: "transparent",
                allowScriptAccess: "always"
            };

            var attr = {
                id: "BugsClipboardUtil"
            };

            swfobject.embedSWF(g_urlSwf + "/BugsClipboardUtil.swf", "BugsClipboardUtil", "100%", "100%", "9.0.0", "expressInstall.swf", flashvars, params, attr, function(e) {
                if (e.success) this.swf = e.ref;
            }.bind(this));
        }
    },

    reposition: function() {
        if (!this.swf) {
            var swf = jQuery("#BugsClipboardUtil")[0];
            if (!swf || swf.tagName == "DIV") return false;

            this.swf = swf;
        }

        var offset = this.button.offset();
        var width = this.button.outerWidth();
        var height = this.button.outerHeight();

        this.container.offset(offset).width(width).height(height);
        if (this.swf.setId) {
            this.swf.setId(this.id);
            this.swf.setCopyData(this.option.copyData);
        }
    },

    setCopyData: function(copyData) {
        this.option.copyData = copyData;

        if (!this.swf) {
            var swf = jQuery("#BugsClipboardUtil")[0];
            if (!swf || swf.tagName == "DIV") return false;

            this.swf = swf;
        }

        if (this.swf.setCopyData) this.swf.setCopyData(this.option.copyData);
    },

    handleEvent: function(e) {
        //alert(e);
        switch (e) {
            case "mouseOver":
                this.button.addClass(this.option.addClass);
                break;
            case "mouseOut":
                this.button.removeClass(this.option.addClass);
                break;
            case "complete":
                this.option.onComplete();
                break;
            case "mouseDown":
                break;
            case "mouseUp":
                break;
        }
    }
};
//-----------------------------------------------------------------------------

bugs.ui.adult = {
    popup: null,
    certTid: null,
    remainTime: 0,

    limit: function() {
        var msg = "<p>해당 곡(or 뮤직비디오)는 청소년 유해매체물로서 <br />19세 미만의 청소년이 이용할 수 없습니다.</p>";
        bugs.ui.showAlert(msg, {
            css: "layerAlert layerMsg layerMember19Msg"
        });
        return;
    },

    notice: function() {
        var msg = "<div class=\"layerAlert layerMsg layerMember19Msg\">" + "	<div class=\"content\">" + "		<p>해당 곡(or 뮤직비디오)는 청소년 유해매체물로서<br />19세 미만의 청소년이 이용할 수 없습니다.</p>" + "		<p>회원님의 연령이 확인되지 않았으므로,<br />아래 버튼을 클릭하여 연령확인을 해주시기 바랍니다.</p>" + "		<div class=\"btnArea\">" + "			<span class=\"button typeME\"><a href=\"javascript:void(0);\" type=\"adultCheck\" >연령 확인</a></span>" + "			<span class=\"button typeM\"><a href=\"javascript:void(0);\" type=\"cancel\" >취소</a></span>" + "		</div>" + "		<div class=\"btnClose\"><a href=\"javascript:void(0);\" type=\"cancel\"><span>닫기</span></a></div>" + "	</div>" + "	<div class=\"layerBg bgTL\"></div>" + "</div>";

        if (!bugs.valid.isNull(this.popup)) this.popup.remove();

        this.popup = new bugs.ui.popup(jQuery(msg), {
            onInit: function(popup) {

                // 연령확인 버튼 클릭
                popup.layer.find("a[type=adultCheck]").click(function() {
                    bugs.ui.adult.popup.hide();
                    bugs.ui.adult.check("age");
                });

            }
        });
        this.popup.show();
    },

    getObjParams: function(popup) {
        if (bugs.valid.isNull(popup)) return null;

        var objParams = {
            phoneNo1: jQuery.trim(popup.layer.find("#phoneNo1").val()),
            phoneNo2: jQuery.trim(popup.layer.find("#phoneNo2").val()),
            phoneNo3: jQuery.trim(popup.layer.find("#phoneNo3").val()),
            phoneNo: "",

            phoneCorp: jQuery.trim(popup.layer.find("input[name=phoneCorp]:checked").val()),

            birthDateYear: jQuery.trim(popup.layer.find("#birthDateYear").val()),
            birthDateMonth: jQuery.trim(popup.layer.find("#birthDateMonth").val()),
            birthDateDay: jQuery.trim(popup.layer.find("#birthDateDay").val()),

            gender: jQuery.trim(popup.layer.find("input[name=gender]:checked").val()),
            nation: jQuery.trim(popup.layer.find("input[name=nation]:checked").val()),
            name: jQuery.trim(popup.layer.find("#name").val()),
            smsNum: jQuery.trim(popup.layer.find("#smsNum").val()),
            certAgreePrivate: (popup.layer.find("input[name=certAgreePrivate]").is(":checked")) ? "Y" : "N",
            certAgreeIdentity: (popup.layer.find("input[name=certAgreeIdentity]").is(":checked")) ? "Y" : "N",

            reSend: jQuery.trim(popup.layer.find("input[name=reSend]").val()),
            check_1: jQuery.trim(popup.layer.find("input[name=check_1]").val()),
            check_2: jQuery.trim(popup.layer.find("input[name=check_2]").val()),
            check_3: jQuery.trim(popup.layer.find("input[name=check_3]").val()),
            CI: jQuery.trim(popup.layer.find("input[name=CI]").val()),
            DI: jQuery.trim(popup.layer.find("input[name=DI]").val())
        };

        objParams.phoneNo = objParams.phoneNo1 + objParams.phoneNo2 + objParams.phoneNo3;

        return objParams;
    },

    checkParams: function(popup, objParams) {

        if (bugs.valid.isNull(popup) || bugs.valid.isNull(objParams)) {
            var msg = "<p>잘못된 접근입니다. 다시 시도해주세요.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                }
            });
            return false;
        }

        if (bugs.valid.isNull(objParams.name)) {
            var msg = "<p>이름을 입력해주세요.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#name").focus();
                }
            });
            return false;
        }

        if (bugs.valid.isNull(objParams.phoneNo1)) {
            var msg = "<p>휴대폰 앞자리를 입력해주세요.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#phoneNo1").focus();
                }
            });
            return false;
        }

        if (bugs.valid.isNull(objParams.phoneNo2)) {
            var msg = "<p>휴대폰 가운데 자리를 입력해주세요.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#phoneNo2").focus();
                }
            });
            return false;
        }

        if (bugs.valid.isNull(objParams.phoneNo3)) {
            var msg = "<p>휴대폰 마지막 자리를 입력해주세요.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#phoneNo3").focus();
                }
            });
            return false;
        }

        if (!bugs.valid.num(objParams.phoneNo)) {
            var msg = "<p>휴대폰 번호는 숫자만 가능합니다.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#phoneNo2").focus();
                }
            });
            return false;
        }

        if (bugs.valid.isNull(objParams.phoneCorp)) {
            var msg = "<p>이동통신사를 선택해주세요.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#phoneCorp").focus();
                }
            });
            return false;
        }

        if (bugs.valid.isNull(objParams.birthDateYear)) {
            var msg = "<p>생년월일을 선택해주세요.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#birthDateYear").focus();
                }
            });
            return false;
        }

        if (bugs.valid.isNull(objParams.birthDateMonth)) {
            var msg = "<p>생년월일을 선택해주세요.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#birthDateMonth").focus();
                }
            });
            return false;
        }

        if (bugs.valid.isNull(objParams.birthDateDay)) {
            var msg = "<p>생년월일을 선택해주세요.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#birthDateDay").focus();
                }
            });
            return false;
        }

        if (bugs.valid.isNull(objParams.gender)) {
            var msg = "<p>성별을 선택해주세요.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#gender").focus();
                }
            });
            return false;
        }

        if (bugs.valid.isNull(objParams.nation)) {
            var msg = "<p>국적을 선택해주세요.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#nation").focus();
                }
            });
            return false;
        }

        if ("Y" != objParams.certAgreePrivate) {
            var msg = "<p>개인정보 이용 및 활용에 동의하셔야 합니다.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#certAgreePrivate").focus();
                }
            });
            return false;
        }

        if ("Y" != objParams.certAgreeIdentity) {
            var msg = "<p>고유식별정보 처리에 동의하셔야 합니다.</p>";
            bugs.ui.showAlert(msg, {
                css: "layerAlert layerMsg",
                onHide: function() {
                    bugs.ui.modalLayer.show();
                    popup.layer.find("#certAgreeIdentity").focus();
                }
            });
            return false;
        }

        return true;

    },

    showCountdown: function(popup, timeToExpiration, reStart) {
        if (reStart != "") clearInterval(this.certTid);

        bugs.ui.adult.remainTime = timeToExpiration - 1;

        if (bugs.ui.adult.remainTime >= -1) {
            var day = Math.floor(timeToExpiration / (3600 * 24));
            var mod = timeToExpiration % (24 * 3600);
            var hour = Math.floor(mod / 3600);
            var mod = mod % 3600;
            var min = Math.floor(mod / 60);
            var sec = mod % 60;

            popup.layer.find("#countDown").html("<em>" + min + "분 " + sec + "초</em>");
            if (bugs.ui.adult.remainTime == -1) {
                popup.layer.find("input, select").attr("disabled", "");
            } else {
                if (popup.layer.find("#authScene").is(":visible") == true) {
                    this.certTid = setTimeout(function() {
                        bugs.ui.adult.showCountdown(popup, bugs.ui.adult.remainTime, "");
                    }, 1000); // will work with every browser
                }
            }
        }
    },

    initData: function(popup) {
        // 데이터 초기화
        popup.layer.find("input[name=check_1]").val("");
        popup.layer.find("input[name=check_2]").val("");
        popup.layer.find("input[name=check_3]").val("");
        popup.layer.find("input[name=CI]").val("");
        popup.layer.find("input[name=DI]").val("");
    },

    initScene: function(popup) {
        // 화면정리
        popup.layer.find("fieldset:eq(0) p.telMsg").empty().hide();

        popup.layer.find("#requestScene").show();
        popup.layer.find("#authScene").hide();

        popup.layer.find("#reqSmsNum").show();
        popup.layer.find("#authSmsNum").hide();

        popup.layer.find("input, select").attr("disabled", "");
    },

    error: function(popup, msg) {
        popup.layer.find("fieldset:eq(0) p.telMsg").empty().html(msg).show();
    },

    popupTerms: function(type) {

        // 고유식별정보 처리 동의 팝업 identity
        if ("identity" == type) {
            var popUp = window.open("https://www.kmcert.com/kmcis/comm/kmcisHpDiscrAgreePop.html", "kmcisHpDiscrAgreePop", "width=445,height=550,toolbar=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0");
            popUp.focus();
        }

        // 개인정보 이용 및 활용 동의 팝업 private
        else {
            var popUp = window.open("https://www.kmcert.com/kmcis/comm/kmcisHpAgreePop.html", "kmcisHpAgreePop", "width=445,height=550,toolbar=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0");
            popUp.focus();
        }

    },

    // type : age, game
    check: function(type) {
        var title = "";
        var comments = "";
        var className = "";

        if ("age" == type) {
            title = "벅스 성인인증";
            comments = "해당 컨텐츠는 청소년에게 유해한 정보를 포함하고 있으므로, 성인인증 절차를 거쳐야 합니다.";
            className = "ic19";
        } else if ("game" == type) {
            title = "본인 확인";
            comments = "게임 채널링 서비스 이용을 위해 본인확인 절차를 거쳐야 합니다.";
            className = "";
        } else if ("musicpd" == type) {
            title = "본인 확인";
            comments = "뮤직 PD 서비스 이용을 위해 본인확인 절차를 거쳐야 합니다.";
            className = "";
        } else {
            title = "본인 확인";
            comments = "회원님의 원할한 서비스 이용을 위해 본인확인 절차를 거쳐야 합니다.";
            className = "";
        }

        var msg = "<p class=\"checkDesc " + className + "\">" + comments + "</p>" + "<fieldset id=\"requestScene\">" + "<input type=\"hidden\" name=\"reSend\" value=\"\" />" + "<input type=\"hidden\" name=\"check_1\" value=\"\" />" + "<input type=\"hidden\" name=\"check_2\" value=\"\" />" + "<input type=\"hidden\" name=\"check_3\" value=\"\" />" + "<input type=\"hidden\" name=\"CI\" value=\"\" />" + "<input type=\"hidden\" name=\"DI\" value=\"\" />" +

        "	<legend>성인인증 절차</legend>" + "	" + "	<p class=\"telMsg dNone\"></p>" + "	" + "	<table class=\"regTB\" summary=\"이 표는 성인인증 입력 표로 이름 입력, 휴대폰 번호 입력, 이동통신사 선택, 생년월일 선택, 성별 선택, 국적 선택을 할 수 있습니다.\">" + "		<caption>성인인증 입력 표</caption>" + "		<tr>" + "			<th scope=\"row\"><label for=\"name\">이름</label></th>" + "			<td><input type=\"text\" id=\"name\" name=\"name\" value=\"\" class=\"text default\" /></td>" + "		</tr>" + "		<tr>" + "			<th scope=\"row\"><label for=\"phoneNo1\">휴대폰 번호</label></th>" + "			<td>" + "				<select name=\"phoneNo1\" id=\"phoneNo1\">" + "					<option value=\"010\" selected=\"selected\">010</option>" + "					<option value=\"011\">011</option>" + "					<option value=\"016\">016</option>" + "					<option value=\"017\">017</option>" + "					<option value=\"018\">018</option>" + "					<option value=\"019\">019</option>" + "				</select>" + "				-" + "				<input type=\"text\" id=\"phoneNo2\" name=\"phoneNo2\" value=\"\" size=\"6\" maxLength=\"4\" />" + "				-" + "				<input type=\"text\" id=\"phoneNo3\" name=\"phoneNo3\" value=\"\" size=\"6\" maxLength=\"4\" />" + "			</td>" + "		</tr>" + "		<tr>" + "			<th scope=\"row\"><label for=\"phoneCorp_SKT\">이동통신사</label></th>" + "			<td class=\"telecom\">" + "				<input type=\"radio\" id=\"phoneCorp_SKT\" name=\"phoneCorp\" class=\"radio\" value=\"SKT\" checked=\"checked\" /><label for=\"phoneCorp_SKT\">SKT</label>" + "				<input type=\"radio\" id=\"phoneCorp_KTF\" name=\"phoneCorp\" class=\"radio\" value=\"KTF\" /><label for=\"phoneCorp_KTF\">KT</label>" + "				<input type=\"radio\" id=\"phoneCorp_LGT\" name=\"phoneCorp\" class=\"radio\" value=\"LGT\" /><label for=\"phoneCorp_LGT\">LGT</label>" + "			</td>" + "		</tr>" + "		<tr>" + "			<th scope=\"row\"><label for=\"birthDateYear\">생년월일</label></th>" + "			<td class=\"birth\">" + "				<label for=\"birthDateYear\">연도 선택</label>" + "				<select name=\"birthDateYear\" id=\"birthDateYear\" class=\"year\">" + "				</select>" + "				<label for=\"birthDateMonth\">월 선택</label>" + "				<select name=\"birthDateMonth\" id=\"birthDateMonth\">" + "				</select>" + "				<label for=\"birthDateDay\">일 선택</label>" + "				<select name=\"birthDateDay\" id=\"birthDateDay\">" + "				</select>" + "			</td>" + "		</tr>" + "		<tr>" + "			<th scope=\"row\"><label for=\"male\">성별</label></th>" + "			<td>" + "				<span><input type=\"radio\" id=\"male\" name=\"gender\" class=\"radio\" value=\"0\" checked=\"checked\" /><label for=\"male\">남</label></span>" + "				<span><input type=\"radio\" id=\"female\" name=\"gender\" class=\"radio\" value=\"1\" /><label for=\"female\">여</label></span>" + "			</td>" + "		</tr>" + "		<tr>" + "			<th scope=\"row\"><label for=\"native\">국적</label></th>" + "			<td>" + "				<span><input type=\"radio\" id=\"native\" name=\"nation\" class=\"radio\" value=\"0\" checked=\"checked\" /><label for=\"native\">내국인</label></span>" + "				<span><input type=\"radio\" id=\"foreigner\" name=\"nation\" class=\"radio\" value=\"1\" /><label for=\"foreigner\">외국인</label></span>" + "			</td>" + "		</tr>" + "	</table>" + "	<p class=\"agreeCheck\"><input type=\"checkbox\" class=\"checkbox\" id=\"certAgreePrivate\" name=\"certAgreePrivate\" value=\"Y\" /><label for=\"certAgreePrivate\"><a href=\"javascript:bugs.ui.adult.popupTerms('private');\">개인정보 이용 및 활용</a>에 동의합니다.</label></p>" + "	<p class=\"agreeCheck\"><input type=\"checkbox\" class=\"checkbox\" id=\"certAgreeIdentity\" name=\"certAgreeIdentity\" value=\"Y\" /><label for=\"certAgreeIdentity\"><a href=\"javascript:bugs.ui.adult.popupTerms('identity');\">고유식별정보 처리</a>에 동의합니다.</label></p>" + "</fieldset>" + "" + "<fieldset id=\"authScene\" class=\"dNone\">" + "	<legend>인증번호 절차</legend>			" + "	<p class=\"telMsg\"><span id=\"showPhoneNo\"></span>로 발송된<br />인증번호 6자리를 입력해주세요.</p>" + "	<table class=\"regTB\" summary=\"이 표는 인증번호 입력을 할 수 있습니다.\">" + "		<caption>인증번호 입력 표</caption>" + "		<tr>" + "			<th scope=\"row\"><label for=\"authno\">인증번호</label></th>" + "			<td><input type=\"text\" id=\"smsNum\" name=\"smsNum\" maxLength=\"6\" class=\"text default\" /></td>" + "		</tr>" + "	</table>" + "	<p class=\"time\">남은시간 <span id=\"countDown\"><em></em></span> 이내에 입력해주세요.</p>" + "	<p class=\"reAuthno\" id=\"reSendSmsNum\" data-reSend=\"Y\">인증번호를 받지 못하셨다면 <a href=\"javascript:void(0);\">인증번호 다시받기</a></p>" + "</fieldset>" + "" + "<div class=\"btnArea\">" + "	<span id=\"reqSmsNum\" data-reSend=\"N\" class=\"button typeME\"><a href=\"javascript:void(0);\">인증번호 요청</a></span>" + "	<span id=\"authSmsNum\" class=\"button typeME\"><a href=\"javascript:void(0);\" type=\"ok\">인증 확인</a></span>" + "	<span class=\"button typeM\"><a href=\"javascript:void(0);\" type=\"cancel\">취소</a></span>" + "</div>" + "<div class=\"btnClose\"><a href=\"javascript:void(0);\" type=\"cancel\"><span>닫기</span></a></div>";

        bugs.ui.showPopup(msg, {
            title: title,
            css: "layerPopup layerAdultCheck",
            onInit: function(popup) {

                // 레이어 창 메세지 변경
                popup.setTitle(title);

                // 초기화
                bugs.ui.adult.initData(popup);
                bugs.ui.adult.initScene(popup);

                var t = new Date();
                var yy = t.getFullYear();

                var optionDateYear = "<option value=\"\">년</option>";
                for (var i = yy; i >= 1900; i--) {
                    optionDateYear += "<option value=\"" + i + "\">" + i + "</option>";
                }

                var optionDateMonth = "<option value=\"\">월</option>";
                for (var i = 1; i <= 12; i++) {
                    optionDateMonth += "<option value=\"" + i + "\">" + i + "</option>";
                }

                var optionDateDay = "<option value=\"\">일</option>";
                for (var i = 1; i <= 31; i++) {
                    optionDateDay += "<option value=\"" + i + "\">" + i + "</option>";
                }

                popup.layer.find("select[name=birthDateYear]").append(optionDateYear);
                popup.layer.find("select[name=birthDateMonth]").append(optionDateMonth);
                popup.layer.find("select[name=birthDateDay]").append(optionDateDay);

                // 인증번호 받기
                popup.layer.find("#reqSmsNum, #reSendSmsNum").click(function(e) {
                    // 재전송 구분
                    if (!bugs.valid.isNull(jQuery(e.currentTarget).attr("data-reSend"))) {
                        popup.layer.find("input[name=reSend]").val(jQuery(e.currentTarget).attr("data-reSend"));
                    }

                    var objParams = bugs.ui.adult.getObjParams(popup);

                    if (bugs.ui.adult.checkParams(popup, objParams)) {

                        // 인증번호 요청
                        jQuery.ajax({
                            type: 'GET',
                            dataType: "jsonp",
                            cache: false,
                            url: g_urlMember + "/cert/request/key?callback=?",
                            data: objParams,
                            success: function(rtnVal) {

                                if (rtnVal.code == "OK") {

                                    // 전달 데이터 입력
                                    if (!bugs.valid.isNull(rtnVal.data)) {
                                        popup.layer.find("input[name=check_1]").val(rtnVal.data.check_1);
                                        popup.layer.find("input[name=check_2]").val(rtnVal.data.check_2);
                                        popup.layer.find("input[name=check_3]").val(rtnVal.data.check_3);
                                        popup.layer.find("input[name=CI]").val(rtnVal.data.CI);
                                        popup.layer.find("input[name=DI]").val(rtnVal.data.DI);

                                        // 모든 입력창 딤드 처리
                                        popup.layer.find("input, select").not("input[name=smsNum]").attr("disabled", "disabled");
                                        popup.layer.find("input[name=smsNum]").focus();

                                        // 화면정리
                                        popup.layer.find("fieldset:eq(0) p.telMsg").empty().hide();

                                        popup.layer.find("#requestScene").hide();
                                        popup.layer.find("#authScene").show();

                                        popup.layer.find("#reqSmsNum").hide();
                                        popup.layer.find("#authSmsNum").show();

                                        // 정보표시
                                        popup.layer.find("#showPhoneNo").text(objParams.phoneNo);
                                        popup.layer.find("#smsNum").focus();

                                        // 카운트
                                        if ("Y" == objParams.reSend) {
                                            bugs.ui.adult.showCountdown(popup, 180, "reStart");
                                        } else {
                                            bugs.ui.adult.showCountdown(popup, 180, "");
                                        }
                                    } else {
                                        var msg = "<p>본인인증 정보를 확인 할 수 없습니다.</p>";
                                        bugs.ui.showAlert(msg, {
                                            css: "layerAlert layerMsg",
                                            onHide: function() {
                                                if (!bugs.valid.isNull(bugs.ui.adult.popup)) bugs.ui.adult.popup.remove();
                                                popup.layer.hide();
                                            }
                                        });
                                        return;

                                    }
                                } else {
                                    switch (rtnVal.code) {
                                        case "ERROR_PARAMETER":
                                            var msg = "<p>" + rtnVal.message + "</p>";
                                            bugs.ui.showAlert(msg, {
                                                css: "layerAlert layerMsg",
                                                onHide: function() {
                                                    bugs.ui.modalLayer.show();
                                                }
                                            });
                                            return
                                            break;

                                        default:
                                            bugs.ui.adult.error(popup, rtnVal.message);
                                            return
                                            break;
                                    }
                                }
                            },
                            error: function() {
                                var msg = "<p>" + title + "에 실패하였습니다.</p>" + "<p>본인 확인 정보를 다시 입력하시기 바랍니다.</p>";
                                bugs.ui.showAlert(msg, {
                                    css: "layerAlert layerMsg",
                                    onHide: function() {
                                        bugs.ui.modalLayer.show();
                                    }
                                });
                                return;
                            }
                        });
                    }
                });
            },
            onOk: function(popup) {

                // 제한시간 확인
                if (bugs.ui.adult.remainTime == -1) {
                    var msg = "<p>승인번호 입력 제한 시간이 지났습니다.<br />인증번호를 다시 받아주세요.</p>";
                    bugs.ui.showAlert(msg, {
                        css: "layerAlert layerMsg",
                        onHide: function() {
                            bugs.ui.modalLayer.show();
                            popup.layer.find("#smsNum").focus();
                        }
                    });
                    return false;
                }

                var objParams = bugs.ui.adult.getObjParams(popup);

                if (bugs.ui.adult.checkParams(popup, objParams)) {

                    if (bugs.valid.isNull(objParams.smsNum)) {
                        var msg = "<p>인증번호를 입력해주세요.</p>";
                        bugs.ui.showAlert(msg, {
                            css: "layerAlert layerMsg",
                            onHide: function() {
                                bugs.ui.modalLayer.show();
                                popup.layer.find("#smsNum").focus();
                            }
                        });
                        return false;
                    }

                    if (objParams.smsNum.length != 6) {
                        var msg = "<p>인증번호 6자리를 정확히 입력해 주세요.</p>";
                        bugs.ui.showAlert(msg, {
                            css: "layerAlert layerMsg",
                            onHide: function() {
                                bugs.ui.modalLayer.show();
                                popup.layer.find("#smsNum").focus();
                            }
                        });
                        return false;
                    }

                    if (bugs.valid.isNull(objParams.check_1) || bugs.valid.isNull(objParams.check_2) || bugs.valid.isNull(objParams.check_3)) {
                        var msg = "<p>인증번호 전송 후 이용하세요.</p>";
                        bugs.ui.showAlert(msg, {
                            css: "layerAlert layerMsg",
                            onHide: function() {
                                bugs.ui.modalLayer.show();
                                popup.layer.find("#smsNum").focus();
                            }
                        });
                        return false;
                    }

                    jQuery.ajax({
                        type: 'GET',
                        dataType: "jsonp",
                        cache: false,
                        url: g_urlMember + "/cert/auth/key?callback=?",
                        data: objParams,
                        success: function(rtnVal) {
                            if (rtnVal.code == "OK") {
                                if (rtnVal.data < 19) {
                                    var msg = "<p>회원님은 19세 미만의 청소년으로 확인되어,<br />해당 서비스를 이용하실 수 없습니다.</p>";
                                    bugs.ui.showAlert(msg, {
                                        css: "layerAlert layerMsg",
                                        onHide: function() {
                                            try {
                                                if (!bugs.valid.isNull(bugs.ui.adult.popup)) bugs.ui.adult.popup.remove();
                                                popup.layer.hide();
                                                location.reload();
                                            } catch (e) {
                                                location.reload();
                                            }
                                        }
                                    });
                                    return
                                } else {
                                    location.reload();
                                }
                            } else {
                                switch (rtnVal.code) {
                                    case "ERROR_PARAMETER":
                                        var msg = "<p>" + rtnVal.message + "</p>";
                                        bugs.ui.showAlert(msg, {
                                            css: "layerAlert layerMsg",
                                            onHide: function() {
                                                bugs.ui.modalLayer.show();
                                            }
                                        });
                                        return;
                                        break;

                                    default:
                                        // 초기화
                                        bugs.ui.adult.initScene(popup);

                                        bugs.ui.adult.error(popup, rtnVal.message);
                                        return;
                                        break;
                                }
                            }
                        },
                        error: function() {
                            var msg = "<p>" + title + "에 실패하였습니다.</p>" + "<p>본인 확인 정보를 다시 입력하시기 바랍니다.</p>";
                            bugs.ui.showAlert(msg, {
                                css: "layerAlert layerMsg",
                                onHide: function() {
                                    bugs.ui.modalLayer.show();
                                }
                            });
                            return;
                        }
                    });

                }
            }
        });
    },

    nullTmp: {}
};



//----------------------------------------------------------------------------- 